package com.xywh.composeLibrary.statex

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import com.xywh.composeLibrary.R
import com.xywh.composeLibrary.ext.ListFloatingActionButton

/**
 * 下拉加载封装
 *
 * implementation "com.google.accompanist:accompanist-swiperefresh:xxx"
 * */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun <T : Any> SwipeRefreshList(
    collectAsLazyPagingItems: LazyPagingItems<T>,
    listContent: LazyListScope.() -> Unit,
) {

    var refresh by remember { mutableStateOf(false) }

    val rememberSwipeRefreshState = rememberPullRefreshState(refresh, {
        collectAsLazyPagingItems.refresh()
    })

    val listState = rememberLazyListState()

    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(rememberSwipeRefreshState)
    ) {

        refresh = collectAsLazyPagingItems.loadState.refresh is LoadState.Loading

        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),

            ) {
            listContent()
            collectAsLazyPagingItems.apply {
                when {
                    loadState.append is LoadState.Loading -> {
                        //加载更多，底部loading
                        item { LoadingItem() }
                    }

                    loadState.append is LoadState.Error -> {
                        //加载更多异常
                        item {
                            ErrorMoreRetryItem() {
                                collectAsLazyPagingItems.retry()
                            }
                        }
                    }

                    loadState.refresh is LoadState.Error -> {
                        if (collectAsLazyPagingItems.itemCount <= 0) {
                            //刷新的时候，如果itemCount小于0，第一次加载异常
                            item {
                                ErrorContent() {
                                    collectAsLazyPagingItems.retry()
                                }
                            }
                        } else {
                            item {
                                ErrorMoreRetryItem() {
                                    collectAsLazyPagingItems.retry()
                                }
                            }
                        }
                    }

                    loadState.refresh is LoadState.Loading -> {
                        // 第一次加载且正在加载中
                        if (collectAsLazyPagingItems.itemCount == 0) {
                        }
                    }
                }
            }

        }
        Box(
            Modifier
                .padding(10.dp)
                .align(Alignment.BottomEnd)
        ) {
            ListFloatingActionButton(rememberCoroutineScope(), listState)
        }
        PullRefreshIndicator(
            refresh,
            rememberSwipeRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}

/**
 * 底部加载更多失败处理
 * */

/**
 * 底部加载更多失败处理
 * */
@Composable
fun ErrorMoreRetryItem(retry: () -> Unit) {
    Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
        TextButton(
            onClick = { retry() },
            modifier = Modifier
                .padding(20.dp)
                .width(200.dp)
                .height(40.dp),
            shape = RoundedCornerShape(6.dp),
            contentPadding = PaddingValues(3.dp),
            colors = ButtonDefaults.textButtonColors(containerColor = MaterialTheme.colorScheme.primary),
        ) {
            Text(text = "请重试", color = Color.White, fontSize = 14.sp)
        }
    }
}

/**
 * 页面加载失败处理
 * */

/**
 * 页面加载失败处理
 * */
@Composable
fun ErrorContent(retry: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 100.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            modifier = Modifier
                .padding(top = 80.dp)
                .height(100.dp),
            painter = painterResource(id = R.drawable.ic_state_empty),
            contentDescription = null
        )
        Text(
            text = "请求失败，请检查网络",
            modifier = Modifier.padding(8.dp),
            color = Color.Gray,
            fontSize = 14.sp
        )
        TextButton(
            onClick = { retry() },
            modifier = Modifier
                .padding(20.dp)
                .width(200.dp)
                .height(40.dp),
            shape = RoundedCornerShape(10.dp),
            contentPadding = PaddingValues(5.dp),
            colors = ButtonDefaults.textButtonColors(containerColor = MaterialTheme.colorScheme.primary)

            //colors = ButtonDefaults
        ) { Text(text = "重试", color = Color.White, fontSize = 14.sp) }
    }
}

/**
 * 底部加载更多正在加载中...
 * */

/**
 * 底部加载更多正在加载中...
 * */
@Composable
fun LoadingItem() {
    Row(
        modifier = Modifier
            .padding(top = 10.dp)
            .height(34.dp)
            .fillMaxWidth()
            .padding(5.dp),
        horizontalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier
                .size(14.dp),
            color = MaterialTheme.colorScheme.primary,
            strokeWidth = 2.dp
        )
        Text(
            text = "加载中...",
            color = Color.Gray,
            modifier = Modifier
                .fillMaxHeight()
                .padding(start = 20.dp),
            fontSize = 14.sp,
        )
    }
}
